// UI state management store

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { STORAGE_KEYS, BREAKPOINTS } from '@/constants'

export const useUIStore = defineStore('ui', () => {
  // State
  const sidebarCollapsed = ref(false)
  const clientInfoVisible = ref(true)
  const activeTab = ref('chats') // 'chats', 'contacts', 'settings'
  const windowWidth = ref(window.innerWidth)
  const windowHeight = ref(window.innerHeight)
  const theme = ref<'light' | 'dark'>('light')
  const loading = ref(false)
  const notifications = ref<Array<{
    id: string
    type: 'success' | 'error' | 'warning' | 'info'
    title: string
    message: string
    duration?: number
    timestamp: Date
  }>>([])

  // Modal and dialog states
  const modals = ref<Record<string, boolean>>({
    userProfile: false,
    settings: false,
    createChat: false,
    fileUpload: false,
    imagePreview: false
  })

  // Layout states
  const layoutStates = ref({
    sidebarWidth: 280,
    clientInfoWidth: 320,
    titlebarHeight: 60,
    tabsWidth: 300
  })

  // Getters
  const isMobile = computed(() => windowWidth.value < BREAKPOINTS.MD)
  const isTablet = computed(() => windowWidth.value >= BREAKPOINTS.MD && windowWidth.value < BREAKPOINTS.LG)
  const isDesktop = computed(() => windowWidth.value >= BREAKPOINTS.LG)

  const shouldHideClientInfo = computed(() => {
    return isMobile.value || (isTablet.value && !clientInfoVisible.value)
  })

  const shouldCollapseSidebar = computed(() => {
    return isMobile.value || sidebarCollapsed.value
  })

  const availableWidth = computed(() => {
    let width = windowWidth.value
    
    if (!shouldCollapseSidebar.value) {
      width -= layoutStates.value.sidebarWidth
    }
    
    if (!shouldHideClientInfo.value) {
      width -= layoutStates.value.clientInfoWidth
    }
    
    return width
  })

  const chatAreaWidth = computed(() => {
    let width = availableWidth.value
    
    if (!isMobile.value) {
      width -= layoutStates.value.tabsWidth
    }
    
    return width
  })

  const unreadNotificationsCount = computed(() => {
    return notifications.value.length
  })

  // Actions
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
    saveUIStateToStorage()
  }

  const setSidebarCollapsed = (collapsed: boolean) => {
    sidebarCollapsed.value = collapsed
    saveUIStateToStorage()
  }

  const toggleClientInfo = () => {
    clientInfoVisible.value = !clientInfoVisible.value
    saveUIStateToStorage()
  }

  const setClientInfoVisible = (visible: boolean) => {
    clientInfoVisible.value = visible
    saveUIStateToStorage()
  }

  const setActiveTab = (tab: string) => {
    activeTab.value = tab
    saveUIStateToStorage()
  }

  const updateWindowSize = (width: number, height: number) => {
    windowWidth.value = width
    windowHeight.value = height
    
    // Auto-adjust layout based on screen size
    if (width < BREAKPOINTS.MD) {
      // Mobile: collapse sidebar and hide client info
      sidebarCollapsed.value = true
      clientInfoVisible.value = false
    } else if (width < BREAKPOINTS.LG) {
      // Tablet: show sidebar but hide client info
      sidebarCollapsed.value = false
      clientInfoVisible.value = false
    } else {
      // Desktop: show everything
      sidebarCollapsed.value = false
      clientInfoVisible.value = true
    }
  }

  const setTheme = (newTheme: 'light' | 'dark') => {
    theme.value = newTheme
    document.documentElement.setAttribute('data-theme', newTheme)
    saveUIStateToStorage()
  }

  const toggleTheme = () => {
    setTheme(theme.value === 'light' ? 'dark' : 'light')
  }

  const setLoading = (isLoading: boolean) => {
    loading.value = isLoading
  }

  // Modal management
  const openModal = (modalName: string) => {
    modals.value[modalName] = true
  }

  const closeModal = (modalName: string) => {
    modals.value[modalName] = false
  }

  const toggleModal = (modalName: string) => {
    modals.value[modalName] = !modals.value[modalName]
  }

  const closeAllModals = () => {
    Object.keys(modals.value).forEach(key => {
      modals.value[key] = false
    })
  }

  const isModalOpen = (modalName: string) => {
    return modals.value[modalName] || false
  }

  // Notification management
  const addNotification = (notification: {
    type: 'success' | 'error' | 'warning' | 'info'
    title: string
    message: string
    duration?: number
  }) => {
    const id = Date.now().toString(36) + Math.random().toString(36).substr(2)
    const newNotification = {
      id,
      ...notification,
      timestamp: new Date(),
      duration: notification.duration || 5000
    }
    
    notifications.value.push(newNotification)
    
    // Auto-remove notification after duration
    if (newNotification.duration > 0) {
      setTimeout(() => {
        removeNotification(id)
      }, newNotification.duration)
    }
    
    return id
  }

  const removeNotification = (id: string) => {
    notifications.value = notifications.value.filter(n => n.id !== id)
  }

  const clearAllNotifications = () => {
    notifications.value = []
  }

  // Layout management
  const updateLayoutState = (updates: Partial<typeof layoutStates.value>) => {
    layoutStates.value = {
      ...layoutStates.value,
      ...updates
    }
    saveUIStateToStorage()
  }

  const resetLayout = () => {
    layoutStates.value = {
      sidebarWidth: 280,
      clientInfoWidth: 320,
      titlebarHeight: 60,
      tabsWidth: 300
    }
    sidebarCollapsed.value = false
    clientInfoVisible.value = true
    saveUIStateToStorage()
  }

  // Storage helpers
  const saveUIStateToStorage = () => {
    const state = {
      sidebarCollapsed: sidebarCollapsed.value,
      clientInfoVisible: clientInfoVisible.value,
      activeTab: activeTab.value,
      theme: theme.value,
      layoutStates: layoutStates.value
    }
    localStorage.setItem(STORAGE_KEYS.UI_STATE, JSON.stringify(state))
  }

  const loadUIStateFromStorage = () => {
    try {
      const stored = localStorage.getItem(STORAGE_KEYS.UI_STATE)
      if (stored) {
        const state = JSON.parse(stored)
        sidebarCollapsed.value = state.sidebarCollapsed ?? false
        clientInfoVisible.value = state.clientInfoVisible ?? true
        activeTab.value = state.activeTab ?? 'chats'
        theme.value = state.theme ?? 'light'
        layoutStates.value = { ...layoutStates.value, ...state.layoutStates }
        
        // Apply theme
        document.documentElement.setAttribute('data-theme', theme.value)
      }
    } catch (err) {
      console.error('Failed to load UI state from storage:', err)
    }
  }

  // Window resize handler
  const handleWindowResize = () => {
    updateWindowSize(window.innerWidth, window.innerHeight)
  }

  // Initialize store
  const initialize = () => {
    loadUIStateFromStorage()
    updateWindowSize(window.innerWidth, window.innerHeight)
    
    // Add window resize listener
    window.addEventListener('resize', handleWindowResize)
  }

  const cleanup = () => {
    window.removeEventListener('resize', handleWindowResize)
  }

  // Keyboard shortcuts
  const handleKeyboardShortcut = (event: KeyboardEvent) => {
    // Ctrl/Cmd + B: Toggle sidebar
    if ((event.ctrlKey || event.metaKey) && event.key === 'b') {
      event.preventDefault()
      toggleSidebar()
    }
    
    // Ctrl/Cmd + I: Toggle client info
    if ((event.ctrlKey || event.metaKey) && event.key === 'i') {
      event.preventDefault()
      toggleClientInfo()
    }
    
    // Ctrl/Cmd + T: Toggle theme
    if ((event.ctrlKey || event.metaKey) && event.key === 't') {
      event.preventDefault()
      toggleTheme()
    }
    
    // Escape: Close all modals
    if (event.key === 'Escape') {
      closeAllModals()
    }
  }

  const enableKeyboardShortcuts = () => {
    document.addEventListener('keydown', handleKeyboardShortcut)
  }

  const disableKeyboardShortcuts = () => {
    document.removeEventListener('keydown', handleKeyboardShortcut)
  }

  return {
    // State
    sidebarCollapsed,
    clientInfoVisible,
    activeTab,
    windowWidth,
    windowHeight,
    theme,
    loading,
    notifications,
    modals,
    layoutStates,
    
    // Getters
    isMobile,
    isTablet,
    isDesktop,
    shouldHideClientInfo,
    shouldCollapseSidebar,
    availableWidth,
    chatAreaWidth,
    unreadNotificationsCount,
    
    // Actions
    toggleSidebar,
    setSidebarCollapsed,
    toggleClientInfo,
    setClientInfoVisible,
    setActiveTab,
    updateWindowSize,
    setTheme,
    toggleTheme,
    setLoading,
    
    // Modal actions
    openModal,
    closeModal,
    toggleModal,
    closeAllModals,
    isModalOpen,
    
    // Notification actions
    addNotification,
    removeNotification,
    clearAllNotifications,
    
    // Layout actions
    updateLayoutState,
    resetLayout,
    
    // Lifecycle
    initialize,
    cleanup,
    enableKeyboardShortcuts,
    disableKeyboardShortcuts
  }
})